from datetime import datetime
from django import forms
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.sites.models import Site
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.defaultfilters import slugify
from django.utils.translation import gettext as _

from models import Document
from os.path import splitext

class DocumentField(forms.FileField):
    def __init__(self, *args, **kwargs):
        super(DocumentField, self).__init__(*args, **kwargs)
        self.label = _(u'Document')
        self.helptext = _(u'Select a doc, odt, txt, rtf, html, xhtml or pdf document')

    def clean(self, data):
        f = super(DocumentField, self).clean(data)
        file_types = ('text/html', 'text/plain', 'text/rtf',
                      'text/xml', 'text/csv', 'application/msword',
                      'application/rtf', 'application/pdf')
        file_exts = ('.odt', '.pdf', '.doc', '.txt',
                     '.html', '.rtf', '.htm', '.xhtml')
        # TODO: Also check the first X bytes of the files to see if
        # their content-types match.
        if not splitext(f.filename)[1].lower() in file_exts \
               and not data['content-type'] in file_types:
            raise forms.ValidationError(_(u'Document types accepted: %s' % ' '.join(file_exts)))
        return f

@login_required
def add_edit_document(request, id=None):
    if id is None:
        DocumentForm = forms.models.form_for_model(Document)
    else:
        doc = Document.objects.get(id=id)
        DocumentForm = forms.models.form_for_instance(doc)

    # These widgets are shown in the Admin view, but not needed by
    # regular users.
    DocumentForm.base_fields['user'].widget = forms.widgets.HiddenInput()
    DocumentForm.base_fields['user'].required = False
    DocumentForm.base_fields['site'].widget = forms.widgets.HiddenInput()
    DocumentForm.base_fields['site'].required = False
    DocumentForm.base_fields['content_type'].widget = forms.widgets.HiddenInput()
    DocumentForm.base_fields['content_type'].required = False
    DocumentForm.base_fields['pub_date'].widget = forms.widgets.HiddenInput()
    DocumentForm.base_fields['pub_date'].required = False
    DocumentForm.base_fields['slug'].widget = forms.widgets.HiddenInput()
    DocumentForm.base_fields['slug'].required = False
    DocumentForm.base_fields['summary'].required = False
    DocumentForm.base_fields['tags'].required = False
    DocumentForm.base_fields['document'] = DocumentField()

    if request.method == 'POST':
        post_data = request.POST.copy()
        post_data.update(request.FILES)
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            doc = form.save(commit=False)
            # The current site we're uploading from
            doc.site = Site.objects.get(id=settings.SITE_ID)
            doc.user = request.user
            doc.pub_date = datetime.now()
            doc.slug = slugify(doc.title)
            # TODO: Find a way to grab the first paragraph of the
            # uploaded document.
            if doc.summary is None:
                doc.summary = 'The first paragraph of the uploaded document.'
            doc.save()
            return HttpResponseRedirect(doc.get_absolute_url())
    else:
        form = DocumentForm()

    return render_to_response('documents/document_add.html', {'form': form})
